package com.wait.onlinepicturecloud.infrastructure.config;


import lombok.extern.slf4j.Slf4j;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
/**
 * @author with葡萄成熟时
 * @version 1.0
 * 包装请求，使 InputStream 可以重复读取
 */


@Slf4j
public class RequestWrapper extends HttpServletRequestWrapper {

    private final String body;

    public RequestWrapper(HttpServletRequest request) {
        super(request);
        // 创建一个 StringBuilder 对象，用于存储请求体
        StringBuilder stringBuilder = new StringBuilder();
        try (InputStream inputStream = request.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
            // 创建一个字符数组，用于存储读取的字符
            char[] charBuffer = new char[128];
            int bytesRead = -1;
            // 循环读取请求体，直到读取完毕
            while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                // 将读取的字符添加到 StringBuilder 对象中
                stringBuilder.append(charBuffer, 0, bytesRead);
            }
        } catch (IOException ignored) {
        }
        // 将 StringBuilder 对象转换为字符串
        body = stringBuilder.toString();
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        // 创建一个 ByteArrayInputStream 对象，用于存储请求体
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
        // 返回一个 ServletInputStream 对象，用于读取请求体
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
            }

            @Override
            public int read() throws IOException {
                // 从 ByteArrayInputStream 对象中读取请求体
                return byteArrayInputStream.read();
            }
        };

    }

    @Override
    public BufferedReader getReader() throws IOException {
        // 返回一个 BufferedReader 对象，用于读取请求体
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }

    public String getBody() {
        // 返回请求体
        return this.body;
    }

}

